import { Component } from "@angular/core";
import { ImagePicker } from '@ionic-native/image-picker';
import { AlertController,LoadingController,NavParams,ActionSheetController  } from 'ionic-angular';

import { AppConfig } from '../../../app/app.config';

import { HttpClient,HttpHeaders } from '@angular/common/http';
import { FileTransfer,FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { NativeStorage } from '@ionic-native/native-storage'; 
import { Camera, CameraOptions } from '@ionic-native/camera';
import { TranslateService } from '@ngx-translate/core';

import { EmailPage } from './email/email'; 
import { NamePage } from './name/name'; 
import { TelPage } from './tel/tel'; 
import { NationalityPage } from './nationality/nationality'; 
import { AddressPage } from './address/address'; 
@Component({
    selector: 'page-my',
    templateUrl: 'my.html',
})

export class MyPage{
    dependentColumns_1 = [
    {
        options: [
            { text: 'Male', value: '1' },
            { text: 'Female', value: '2' },
        ]
    }
    ];
    dependentColumns_2 = [
    {
        options: [
            { text: 'Student', value: '1' },
            { text: 'Professional', value: '2' },
            { text: 'Other', value: '0' },
        ]
    }
    ];
    pushData:any;
    
    loading:any;
    emailPage=EmailPage;
    addressPage=AddressPage;
    namePage=NamePage;
    telPage=TelPage;
    nationalityPage=NationalityPage;
    userInfo = {
        avatar: '',
        firstname: '',
        email: '',
        address:'',
        gender:1,
        type:0
    }
    
    token:any
    src:any
    constructor(
        private imagePicker:ImagePicker,
        private loadingCtrl:LoadingController,
        private alertCtrl:AlertController,
        private transfer:FileTransfer,
        private http: HttpClient,
        private navParams: NavParams,
        private storage: NativeStorage,
        private camera: Camera,
        private sheet:ActionSheetController,
        private translate: TranslateService,
    ) {
        this.src = AppConfig.getMainUrl()
        this.userInfo = this.navParams.get('userInfo');
        this.userInfo['header'] =  AppConfig.getMainUrl()+this.userInfo['avatar'];
        this.storage.getItem('token').then(token=>{
            this.token = token;
        })
        this.pushData = {
            info: this.userInfo,
            callback: (data)=>{
                if(data.key=="firstname"){
                    let callback = this.navParams.get('callback');
                    callback({firstname:data.value})
                }
                this.userInfo[data.key] = data.value;
            }
        }
        translate.setDefaultLang('en')
    }
    ionViewDidEnter(){
        this.storage.getItem('lang').then(res=>{
            this.translate.use(res)
        })
        this.storage.getItem('token').then(token=>{
            this.http.get(AppConfig.getUrl()+'user/getInfo?token='+token).subscribe(res=>{
                if(res['code']==101){
                    this.userInfo = res['data']
                }
            })
        })
    }
    loadWait(){
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        this.loading.present();
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    imgSelect(){
        let actionSheet = this.sheet.create({
            title: 'Edit avatar',
            buttons: [
              {
                text: 'Camera',
                role: 'destructive',
                handler: () => {
                    const options: CameraOptions = {
                        quality: 100,
                        encodingType: this.camera.EncodingType.JPEG,
                        mediaType: this.camera.MediaType.PICTURE,
                        allowEdit: true,
                        targetWidth:100,
                        targetHeight:100,
                    }
                    this.camera.getPicture(options).then((imageData) => {
                        let fileTransfer: FileTransferObject = this.transfer.create();
                        let options:FileUploadOptions = {
                            fileKey: 'img',
                            chunkedMode: false,
                        }
                        fileTransfer.upload(imageData, AppConfig.getUrl()+'login/upload_avatar',options,true).then((data) => {
                            let response = JSON.parse(data.response) 
                            if(response['code']==101){
                                this.userInfo.avatar = response['data']['thumb_img']
                                let callback = this.navParams.get('callback');
                                callback({avatar:this.userInfo.avatar})
                            }else{
                                this.alertb('Upload failed','');
                            }
                            this.loading.dismiss();
                        }, (err) => {
                            this.alertb('Upload failed','');
                            this.loading.dismiss();
                        })
                    }, (err) => {
                        console.log('未选取')
                    });
                }
              },
              {
                text: 'Select in album',
                handler: () => {
                    this.imagePicker.getPictures({maximumImagesCount:1}).then((results)=>{
                        if(!!results.length){
                            this.loadWait();
                            for (var i=0;i<results.length;i++){
                                let fileTransfer: FileTransferObject = this.transfer.create();
                                let options:FileUploadOptions = {
                                    fileKey: 'img',
                                    chunkedMode: false,
                                }
                                fileTransfer.upload(results[0], AppConfig.getUrl()+'login/upload_avatar',options,true).then((data) => {
                                    let response = JSON.parse(data.response) 
                                    if(response['code']==101){
                                        this.userInfo.avatar = response['data']['thumb_img']
                                        let callback = this.navParams.get('callback');
                                        callback({avatar:this.userInfo.avatar})
                                    }else{
                                        this.alertb('Upload failed','');
                                    }
                                    this.loading.dismiss();
                                }, (err) => {
                                    this.alertb('Upload failed','');
                                    this.loading.dismiss();
                                })
                            }
                        }
                    })
                }
              },
              {
                text: 'Cancel',
                role: 'cancel',
                handler: () => {
                  console.log('Cancel clicked');
                }
              }
            ]
        });
       
        actionSheet.present();
        
        
    }
    editGender(){
        this.http.post(AppConfig.getUrl()+'login/edit?token='+this.token, AppConfig.urlEcode({gender:this.userInfo.gender}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
        .subscribe( res => {
            if(res['code']===101){
                
            }else if(res['code']===202){
                this.alertb('Error!',res['msg']);
            }
        })
    }
    editStatus(){
        this.http.post(AppConfig.getUrl()+'user/edit?token='+this.token, AppConfig.urlEcode({type:this.userInfo.type}), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
        .subscribe( res => {
            if(res['code']===101){
                
            }else if(res['code']===202){
                this.alertb('Error!',res['msg']);
            }
        })
    }
    // editEmail(){
    //     this.http.post(AppConfig.getUrl()+'login/edit?token='+this.token, AppConfig.urlEcode(this.info), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
    //     .subscribe( res => {
    //         if(res['code']===101){
                
    //         }else if(res['code']===202){
    //             this.alertb('failed!',res['msg']);
    //         }
    //     })
    // }
}